require 'pathname'

module Dior
  class Builder
    def initialize
      @config = Configuration.current
      @context = Context.new(@config)
    end

    def process_all
      root_dir = Pathname(@config.source_dir)
      Dir.glob(root_dir + '**/*.dior') do |path|
        @context.evaluate File.read(path)
      end
    end

    def concat
      process_all

      content = @context.each_component
                        .map { |component| assign_js_variable(component) }
                        .join("\n")

      <<-JAVASCRIPT
      (function () {
        #{content}
      })();
      JAVASCRIPT
    end

    private

    def assign_js_variable(component)
      return component.content if component.global?

      <<-JAVASCRIPT
      var #{component.name} = #{component.content};
      JAVASCRIPT
    end
  end
end